<template>
  <div ref="BaseEventTableRef" v-loading="listLoading" class="customer-task-table-container">
    <div class="action-button-group">
      <span class="el-dropdown-link cur-point" @click="() => openSelectColumn()">
        {{$t('common.base.choiceCol')}}
        <i class="iconfont icon-fdn-select"></i>
      </span>
    </div>

    <!-- 表格Start -->
    <el-table
      ref="tasble"
      class="mt_12 bbx-normal-list-box"
      stripe
      :data="eventList"
      :highlight-current-row="false"
      :border="true"
      @sort-change="sortChange"
      @header-dragend="headerDragend"
      v-loading="loading"
      header-row-class-name="common-list-table-header__v2"
      :height="tableHeight"
    >
      <template slot="empty">
        <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>
      <template v-for="column in columns">
        <el-table-column
          v-if="column && column.show"
          :show-overflow-tooltip="getCommonListShowTooltip(column)"
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
          :fixed="column.fixLeft || false"
        >
          <template slot-scope="scope">
            <!-- 处理示例数据 -->
            <template v-if="column.field === 'eventNo'">
              <sample-tooltip :row="scope.row">
                <template slot="content" slot-scope="{isContentTooltip}">
                  <el-tooltip
                    :content="scope.row[column.field]"
                    placement="top"
                    :disabled="!isContentTooltip"
                  >
                    <div>
                      <span :class="[allowEventViewDetail ? 'view-detail-btn' : 'view-detail-btn-disabled']" class="task-list-numbering" @click="openEventDetailTab(scope.row.id, scope.row.eventNo)">
                        {{ scope.row[column.field] }}
                      </span>
                      <span v-if="scope.row.inApprove == 1" class="task-state-block__v2 task-state-block__v2-approve task-font12">
                        {{$t('common.event.approveStatus.approve')}}</span>
                      <span v-if="scope.row.isOverTime == 1" class="task-state-block__v2 task-state-block__v2-overtime task-font12">
                        {{$t('common.event.exceptionStatus.overTime')}}
                      </span>
                    </div>
                  </el-tooltip>
                </template>
              </sample-tooltip>
            </template>
            <template v-else-if="column.renderCell">
              <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
            </template>
            <template v-else-if="column.formType === 'connector'">
              <div v-if="scope.row.attribute && scope.row.attribute[column.field]" class="view-detail-btn task-client" @click.stop="openConnectorDialog(column, scope.row)">
                {{ $t('common.base.view') }}
              </div>
            </template>
            <template v-else-if="column.isSystem === 1">
              {{ $formatFormField(column, scope.row) }}
            </template>

            <template v-else-if="column.formType === 'relationCustomer' && scope.row.attribute[column.field] && column.setting && (column.setting.formType === 'user' || column.setting.fieldName === 'customerManager')">
              <template v-if="isOpenData">
                <open-data v-for="staffId in getUserIds(scope.row.attribute[column.field])" :key="staffId" type="userName" :openid="staffId"></open-data>
              </template>
              <template v-else>
                {{ getUserName(scope.row.attribute[column.field]) }}
              </template>
            </template>

            <template v-else-if="column.formType === 'logistics'">
              <biz-list-logistics-no
                :row="scope.row"
                :column="column"
                :is-link="isCanLogisticsNoLink(column)"
                mode="event"
                :biz-id="scope.row.id"
              />
            </template>

            <template v-else-if="column.formType === 'user' && scope.row.attribute[column.field]">
              <template v-if="isOpenData">
                <open-data v-for="staffId in getUserIds(scope.row.attribute[column.field])" :key="staffId" type="userName" :openid="staffId"></open-data>
              </template>
              <template v-else>
                {{ getUserName(scope.row.attribute[column.field]) }}
              </template>
            </template>

            <template v-else-if="['relationCustomer', 'relationProduct'].includes(column.formType) && (column.setting || {}).formType === 'cascader'">
              {{ (scope.row.attribute[column.field]) | fmt_form_cascader((column.setting || {}).isMulti)}}
            </template>

            <template v-else-if="column.formType === 'phone'">
              <div>
                {{ scope.row.attribute[column.field] }}
                <i
                  v-if="hasCallAuth && callCenterModule && scope.row.attribute[column.field]"
                  class="iconfont icon-fdn-phone color-primary cur-point"
                  title="拨打电话"
                  @click="makePhoneCall(scope.row.attribute[column.field])"
                ></i>
              </div>
            </template>
            <!-- 富文本 -->
            <template v-else-if="column.formType === 'richtext'">
              <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                <span v-if="scope.row.attribute && scope.row.attribute[column.field]">{{$t('common.base.view')}}</span>
              </div>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>

          </template>
        </el-table-column>
      </template>
    </el-table>
    <!-- 表格End -->

    <!-- 分页Start -->
    <BaseAddOnPagination :paginationInfo="searchModel" @pageJump="jump" @sizeChange="handleSizeChange" />
    <!-- 分页End -->

    <!-- start 选择列设置 -->
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    <!-- end 选择列设置 -->

    <!--查看富文本 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>

    <!-- 连接器明细弹窗 -->
    <connector-table-dialog ref="connectorDialogRef" />
  </div>
</template>

<script>
/* mixins*/
import SelectColumnMixin from 'src/mixins/selectColumnMixin/select-column-mixin.js'
import EventListMixin from 'src/modules/event/eventList/event-list-mixin.js'
/* api*/
import { queryEventPageInfo, calendarEventShow, getEventOfCustomer } from '@src/api/EventApi.js'
import { getEventOfProduct } from "@src/api/ProductApi";
/* utils*/
import { getColumnFields } from "@src/modules/event/eventList/fields";
/* service */
import { smoothLogisticsField } from '@service/LogisticsService'
// 接口
const Interface = {
  project: getEventOfProduct,
  customer: getEventOfCustomer,
}
// 默认显示的字段
const Field_Default_Show = {
  project: ['eventNo', 'eventType', 'eventExecutor', 'eventState', 'eventCreateTime', 'eventCompleteTime', 'eventSuggestion'],
  customer: ['eventNo', 'eventType', 'eventExecutor', 'eventState', 'eventCreateTime']
}
// 产品支持排序
const Project_Sort = {
  eventExecutor: 'executor',
  eventSuggestion: 'suggestion',
}
// 客户支持排序
const Customer_Sort = {
  eventExecutor: 'executor',
  eventState: 'state',
}
export default {
  name: 'BaseEventTable',
  mixins: [SelectColumnMixin, EventListMixin],
  props: {
    otherParams: {
      type: Object,
      default: (() => {})
    },
    module: {
      type: String,
      default: ''
    },
  },
  computed: {
    // 第一次进来默认显示哪些字段（产品和客户详情的事件列表需要保证只默认显示之前的字段）
    showFields() {
      return Field_Default_Show?.[this.module] ?? []
    },
    /** 事件列表字段 */
    eventListFields() {
      let columnFields = getColumnFields(this)?.map(item => {
        // 处理默认显示的值
        item.show = this.showFields.includes(item.fieldName) ?? false
        // 处理产品是否支持排序
        if(this.module === 'project' && Object.keys(Project_Sort)?.includes(item.fieldName)) {
          item.sortable = 'custom'
          item.sortName = Project_Sort?.[item.fieldName] ?? ''
        }
        // 处理客户是否支持排序
        if(this.module === 'customer' && Object.keys(Customer_Sort)?.includes(item.fieldName)) {
          item.sortable = 'custom'
          item.sortName = Customer_Sort?.[item.fieldName] ?? ''
        }
        return item
      });

      // 如果开启客户满意度过滤掉满意度、服务标签、客户评价
      if(this.customerSatisfaction) {
        columnFields = columnFields.filter(f=> !['tagEvaluates', 'eventDegree', 'eventSuggestion'].includes(f.fieldName ))
      }

      const taskRelevantFieldNames = [
        'isEventRelevance',
        'isTransferToTask',
      ]
      columnFields = columnFields.filter(field => {

        if (taskRelevantFieldNames.includes(field.fieldName)) {
          return this._isShowTaskModule;
        }

        return true;

      })

      if(!this.eventPlanningBtn){
        columnFields = columnFields.filter(x=>{
          return x.sortName != 'planStartTime' && x.sortName != 'planEndTime';
        })
      }

      return columnFields.sort((a, b) => a.orderId - b.orderId);
    },
  },
  data() {
    return {
      columns: [],
      eventList: [],
      loading: false,
      listLoading: false,
      eventPlanningBtn: false,
      allEventFields: [],
      searchModel: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
        orderDetail: {}
      },
      tableHeight: '300px',
    }
  },
  methods: {
    /*查询事件自定义字段*/
    async getAllEventFields() {
      try {
        const query = { isOrderList : false, isAllTemplate: true }
        const params = { pageSize : 10 , templateId: ''}

        const { data, succ } = await queryEventPageInfo(query, params)
        if(!succ) return

        const fields = this.handlerCustomFields(data?.allEventFields ?? [])
        this.allEventFields = smoothLogisticsField(fields)
        this.initData = data

      } catch (e) {
        console.error('get event all fields error', e)
      }
    },

    /*获取列表字段*/
    async buildColumns() {
      try {
       const localColumns = await this.getLocalColumns();

        let eventListFields = this.eventListFields // 本地默认的表格项字段

        const { evaluateConfig={} } = this.initData
        if(!this.customerSatisfaction && evaluateConfig.useStarEvaluate) { // 如果有服务标签等 构建额外的服务评价列表项
          eventListFields = eventListFields.concat(this.buildExtraEvaluateColumns(false))
        }

        let fields = eventListFields.concat(this.allEventFields); // 拼接不同【事件类型】对应的表格项字段

        fields = this.buildSortFields(fields, localColumns)

        this.columns = []
        this.$nextTick(() => {
          this.$set(this, 'columns', fields.slice())
        })
      } catch (e) {
        console.error(e)
      }
    },

    /*初始化*/
    async initEvent() {
      try {
        this.listLoading = true;

        // 处理选择列的key
        this.getSelectKey('productEvent', true);

        this.getAuthByRootInitData();

        let eventCalendar = await calendarEventShow();
        this.eventPlanningBtn = eventCalendar.data;

        // 获取表单
        await this.getAllEventFields();

        await this.buildColumns();

        await this.fetchData();
      } catch (e) {
        console.error(e)
      } finally {
        this.listLoading = false
      }
    },

    /*查询事件列表*/
    async fetchData() {
      try {
        this.loading = true;

        const {pageNum, pageSize, orderDetail } = this.searchModel;
        const params = {
          pageNum,
          pageSize,
          ...this.otherParams,
        };

        if (Object.keys(orderDetail).length) {
          params.orderDetail = orderDetail;
        }

        const { list, total } = await Interface?.[this.module](params)

        this.eventList = list;

        this.searchModel.totalItems = total;
      } catch (e) {
        console.error(e)
      } finally {
        this.setTableHeight();
        this.loading = false;
      }
    },

    /*翻页*/
    jump(pN) {
      this.searchModel.pageNum = pN;
      this.fetchData();
    },

    /*修改页码*/
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.fetchData();
    },

    /*排序*/
    sortChange({column, order, prop}) {
      const sortedField = this.columns.filter((item) => item.fieldName === prop)[0] || {};
      if(column === null) {
        this.searchModel.orderDetail = {};
      }else{
        this.searchModel.orderDetail = {
          column: sortedField.sortName || sortedField.fieldName,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          type: sortedField.dataType || sortedField.formType,
          isSystem: sortedField.isSystem,
        }
      }
      this.fetchData();
    },

    /*计算表格的高度*/
    setTableHeight() {
      this.$nextTick(() => {
        const tableRect = this.$refs.BaseEventTableRef?.getBoundingClientRect();

        if(!tableRect) return;

        const bodyClient = document.body.clientHeight;
        const top = tableRect.top;
        const paginationHeight = 56;
        const rootContainerPadding = 12;
        const tableContentPaddingTop = 12;

        this.tableHeight =  bodyClient - top - paginationHeight - rootContainerPadding - tableContentPaddingTop - 36
      })
    },

  },
  mounted() {
    this.initEvent()
    window.addEventListener('resize', this.setTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight);
  }
}
</script>

<style lang="scss" scoped>

</style>